package {
	
	import org.flixel.FlxSprite;
	import org.flixel.FlxG;
	public class NiloFader extends FlxSprite {
		
		private var fadeIn:Boolean;
		private var begin:Boolean;
		private var fadeTime:Number, fadeTimeRemaining:Number, callback:Function;
		
		public function NiloFader(X:Number = 0, Y:Number = 0, Width:Number = -1, Height:Number = -1, fadeColor:uint = 0xff000000){
			super(X, Y);
			makeGraphic(Width == -1 ? FlxG.width : Width, Height == -1 ? FlxG.height : Height, fadeColor);
			this.begin = false;
		}
		
		override public function update():void {
			super.update();
			if (begin){
				if (fadeTimeRemaining <= 0){	
					if (this.callback != null){
						if (this.callback.length >= 1){
							this.callback(this);
						}
						else {
							this.callback();
						}
					}
				}
				else {
					fadeTimeRemaining -= FlxG.elapsed;
					if (fadeTimeRemaining < 0) fadeTimeRemaining = 0;
					alpha = fadeIn ? (fadeTimeRemaining / fadeTime) : 1 - (fadeTimeRemaining / fadeTime);	
				}
			}
		}
		
		public function executeFade(fadeIn:Boolean, time:Number, callback:Function = null):NiloFader {
			this.revive();
			fadeTime = time;
			fadeTimeRemaining = time;
			begin = true;
			this.callback = callback;
			this.fadeIn = fadeIn;
			alpha = fadeIn ? 1 : 0;
			return this;
		}
	
	}
}
